package com.tju.resource.oauth.controller.tb;

import com.tju.resource.annotation.Log;
import com.tju.resource.business.tb_supplier.TbSupplierService;
import com.tju.resource.model.TbSupplier;
import com.tju.resource.result.Result;
import com.tju.resource.result.ResultEnum;
import com.tju.resource.result.ResultUtil;
import com.tju.resource.result.SimpleXls;
import com.tju.resource.tool.enum_utils.FunctionType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
public class TbSupplierImportController {

    private final String prefix = "sup";

    @Autowired
    TbSupplierService service;

    public static final Map<String, String> keyToBean = new HashMap<>() {{
        put("供应商代码", "supplierCode");
        put("供应商名称", "supplierName");
        put("联系人", "contact");
        put("供应商地址", "supplierAddress");
        put("供应商电话", "supplierPhone");
        put("供应商传真号码", "supplierFaxPhone");
        put("运输方式", "supplierTp");
        put("备注", "remark");
        put("更新时间", "updateTime");
    }};

    @PreAuthorize("hasAuthority('sys:spClient:supplier:import')")
    @PostMapping(prefix + "/import")
    @Log(type = FunctionType.Import)
    public Result<Object> importData(@RequestParam Map<String, String> params, @RequestParam("file") MultipartFile file) {
        try {
            return SimpleXls.saveAsBeans(
                    TbSupplier.class
                    , keyToBean
                    , file.getInputStream()
                    , service::addSupplier
                    , tbSupplier -> tbSupplier.setCreateBy(params.get("createBy")));
        } catch (IOException e) {
            e.printStackTrace();
            return ResultUtil.error(ResultEnum.UNKONW_ERROR, e.toString());
        }
    }

}
